package com.example.loginregister.presentation;

import com.example.loginregister.business.UserBusinessService;

import com.example.loginregister.dto.UserLoginDto;
import com.example.loginregister.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter out = response.getWriter();

        try {
            // 使用Jackson的ObjectMapper来解析JSON数据
            ObjectMapper objectMapper = new ObjectMapper();
            // 从请求体中读取数据并转换为字符串
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder requestBody = new StringBuilder();
            String line;
            while ((line = reader.readLine())!= null) {
                requestBody.append(line);
            }
            String jsonData = requestBody.toString();
            // 创建用于接收JSON数据的实体类对象（假设已创建UserLoginDto类，和之前提到类似）
            UserLoginDto userLoginDto = objectMapper.readValue(jsonData, UserLoginDto.class);

            UserBusinessService userBusinessService = new UserBusinessService();
            User user = new User();
            user.setUsername(userLoginDto.getUsername());
            user.setPassword(userLoginDto.getPassword());
//            boolean loginResult = userBusinessService.loginUser(userLoginDto.getUsername(), userLoginDto.getPassword());
            boolean loginResult = userBusinessService.loginUser(user);

            if (loginResult) {
                out.println("{\"success\": true, \"message\": \"登录成功\"}");
            } else {
                out.println("{\"success\": false, \"message\": \"用户名或密码错误，请重新输入\"}");
            }
        } catch (IOException e) {
            e.printStackTrace();
            out.println("{\"success\": false, \"message\": \"解析请求数据出错，请检查数据格式并重新尝试\"}");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}